<?php

namespace backend\models;

use Yii;

/**
 * This is the model class for table "user_wallet".
 *
 */
class UserWalletModel extends \backend\base\BaseModel
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'user_wallet';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['user_id', 'coin', 'created_at'], 'integer'],
            [['teacher_income', 'org_income'], 'double', 'message' => '{attribute}格式错误'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'user_id' => '用户ID',
            'coin' => '鼠币',
            'teacher_income' => '老师资金',
            'org_income' => '机构资金',
            'created_at' => '创建时间',
        ];
    }

    /**
     * 获取用户资金
     * @param string $field
     * @param int $user_id
     */
    public static function getIncome($field = 'coin,teacher_income,org_income',$user_id=0)
    {
        if(!$user_id){
            $user_id = 0;
        }
        $res = self::find()->select($field)->where(['user_id'=>$user_id])->asArray()->one();
        if(!$res){
            return 0;
        }
        if(count($res) == 1){
            return $res[$field];
        }
        return $res;
    }

    /**
     * 添加收益
     * @param $income
     * @param string $type
     * @param $user_id
     * @return bool
     */
    public static function addIncome($income,$type='coin',$user_id)
    {
        if($income <= 0){
            return false;
        }
        if(!$user_id){
            return false;
        }
        $info = self::find()->where(['user_id'=>$user_id])->one();
        if(!$info || !isset($info->$type)){
            return false;
        }
        $info->$type += $income;
        if($info->save()){
            return true;
        }
        return false;
    }

    /**
     * 扣除收益
     * @param $income
     * @param string $type
     * @param $user_id
     * @return bool
     */
    public static function decIncome($income,$type='coin',$user_id)
    {
        if($income <= 0){
            return false;
        }
        if(!$user_id){
            return false;
        }
        $info = self::find()->where(['user_id'=>$user_id])->one();
        if(!$info || !isset($info->$type)){
            return false;
        }
        $info->$type -= $income;
        if($info->save()){
            return true;
        }
        return false;
    }
}
